<template>

  <div>
      <el-button type="primary" @click="state.dialogFormVisible = true">新建连接</el-button>
      <el-button type="info" @click="appUpdateStatusFun">启用/停用</el-button>
      <el-button type="danger" @click="appDelete">删除</el-button>
  </div>
  <br>

  <div>
    <el-table
        ref="multipleTableRef"
        :data="state.tableData"
        :border="true" 
        style="width: 100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
    >
        <el-table-column type="selection" width="55" />

        <el-table-column property="name" label="连接名称" width="120" />
        <el-table-column property="applicationName" label="绑定APP" />
        <el-table-column label="状态">
            <template #default="scope">
                <el-tag v-if="scope.row.status == 'Enable' " size="small" type="primary">启用</el-tag>
                <el-tag v-else-if="scope.row.status == 'Disable'" size="small" type="warning">停用</el-tag>
                <el-tag v-else-if="scope.row.status == 'Delete'" size="small" type="danger">删除</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template #default="scope">{{ new Date(scope.row.createDate).toLocaleString() }}</template>
        </el-table-column>
        
    </el-table>
  </div>
  
  <el-dialog v-model="state.dialogFormVisible" title="新建连接" width="500" @close="dialogClose">
    <el-form :model="state.form">
      <el-form-item label="连接名称" :label-width="state.formLabelWidth">
        <el-input v-model="state.form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="绑定APP" :label-width="state.formLabelWidth">
        <el-select v-model="state.form.applicationId" placeholder="请选择客户端类型">
          <el-option v-for="(item,index) in state.deviceTypeList " :label="item.name" :value="item.id" v-bind:key="index" ></el-option>
        </el-select>
      </el-form-item>

      

      <el-form-item label="连接类型" :label-width="state.formLabelWidth">
        <el-select v-model="state.form.type" placeholder="请选择客户端类型">
          <el-option label="内部连接" value="0" ></el-option>
          <el-option label="外部连接" value="1" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="state.form.type=='1'" label="连接URL" :label-width="state.formLabelWidth">
        <el-input v-model="state.form.url" autocomplete="off" @input="filterInput"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button type="primary" @click="saveLinkFun">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script lang="ts" setup>

import { defineComponent,reactive, ref, toRefs , watchEffect , onMounted } from 'vue'
import { ElMessage, ElMessageBox , ElLoading , genFileId , ElTable } from 'element-plus';
import { downloadLinkList , saveLink , updateLinkStatus , getAppList } from '@/axios/api'
const multipleTableRef = ref<InstanceType<typeof ElTable>>()

let loading:any = null;
const openLoading = function(){
  loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}
const closeLoading = function(){
  loading && loading.close();
}


const state = reactive({
    tableData: [
      // {
      //   id:"",
      //   application:"",
      //   name:"",
      //   url:"",
      //   applicationId:"",
      //   applicationName:"",
      //   status:"",
      //   createDate:""
      // }
    ],

    form :{
      name: '',
      applicationId: '',
      type:'',
      url:""
    },
    dialogFormVisible:false,
    formLabelWidth:'140px',
    deviceTypeList:[
      {
        name:"",
        id:""
      }
    ]

})

const initTableData = function(){
  downloadLinkList().then((res:any)=>{
    state.tableData = res.data.data;
  }).catch(err=>{
    ElMessage(err.message)
  })
}

onMounted(()=>{
  initTableData();
  //获取应用列表
  getAppList().then((res:any)=>{
      state.deviceTypeList = res.data.data;
    }).catch(err=>console.log(err))
})

const dialogClose = function(){
    state.form.name = '';
    state.form.applicationId = '';
    state.dialogFormVisible = false;
}

const saveLinkFun = function(){
  if(state.form.type == '1' && !state.form.url){ //外部连接
    ElMessage('外部连接必填');
    return;
  }
  openLoading();
  saveLink(
    {
      name:state.form.name,
      applicationId:state.form.applicationId,
      type:state.form.type,
      url:state.form.url
    }
  ).then(res=>{
    closeLoading();
    dialogClose();
    initTableData();
  }).catch(err=>{
    closeLoading();
    ElMessage(err.message);
  })
}
//表格只选择一行
const handleSelectionChange = (rowData:any) => {
  if(rowData.length > 1){
      multipleTableRef.value!.clearSelection();
      multipleTableRef.value!.toggleRowSelection(rowData.pop(),true);
  }
}
const filterInput = function(){
  state.form.url = state.form.url.replace(/[\u4e00-\u9fa5]/g, '');
}

// --------版本内启用停用逻辑
const appUpdateStatusFun = function(){
    const selectRows = multipleTableRef.value?.getSelectionRows();
    const rowId = selectRows[0].id;
    const rowStatus = selectRows[0].status;
    const newStatus = rowStatus == 'Enable' ? 'Disable' : 'Enable';
    const applicationId = selectRows[0].applicationId;
    updateLinkStatus(
      {
        id:rowId,
        status:newStatus,
        applicationId:applicationId
    }
    ).then((res:any)=>{
        const data = res.data;
        if(data.code == -1){
          ElMessage(data.message);
          return;
        }
        state.tableData.forEach((item:any)=>{
            if(item.id == rowId){
                item.status = newStatus;
            }
        });
    }).catch((err:any)=>{
        ElMessage(err.message);
    })
}

// ----------删除逻辑
const appDelete = function(){
    const selectRows = multipleTableRef.value?.getSelectionRows();
    const rowId = selectRows[0].id;
    updateLinkStatus(
      {
        id:rowId,
        status:'Delete'
      }
    ).then(res=>{
        state.tableData = state.tableData.filter((item:any)=>{
            return item.id != rowId;
        });
    }).catch(err=>{
        ElMessage(err.message);
    })
}


</script>

<style lang="scss" scoped>
  //隐藏表格多选
:deep(.el-table th.el-table__cell:nth-child(1) .cell){
    visibility: hidden;
}

</style>